<template>
	<div class="container">
		<Breadcrumb :items="['menu.biz', 'menu.biz.index']" />
		<a-card :title="$t('menu.biz.index')">
			<a-space fill direction="vertical">
				<!-- 搜索表单 -->
				<a-form layout="inline" :model="searchForm" @submit="handleSearch">
					<a-form-item field="search" label="搜索关键词" :hide-label="true">
						<a-input v-model="searchForm.search" placeholder="搜索商家名称、统一信用代码号或手机号码" allow-clear />
					</a-form-item>
					<a-form-item field="tag_ids" label="标签筛选" :hide-label="true">
						<a-select v-model="searchForm.tag_ids" placeholder="请选择标签" multiple allow-clear
							style="width: 300px;">
							<a-option v-for="tag in allTags" :key="tag.id" :value="tag.id" :label="tag.name">
								{{ tag.name }}
							</a-option>
						</a-select>
					</a-form-item>
					<a-form-item field="multi_biz_id" label="总店筛选" :hide-label="true">
						<a-select v-model="searchForm.multi_biz_id" placeholder="请选择总店"  allow-clear
							style="width: 300px;">
							<a-option v-for="tag in multiList" :key="tag.id" :value="tag.id" :label="tag.name">
								{{ tag.name }}
							</a-option>
						</a-select>
					</a-form-item>
					<a-form-item>
						<a-space>
							<a-button type="primary" html-type="submit" shape="round">
								<template #icon><icon-search /></template>
								搜索
							</a-button>
							<a-button shape="round" @click="resetSearch">
								<template #icon><icon-refresh /></template>
								重置
							</a-button>
						</a-space>
					</a-form-item>
				</a-form>

				<a-row :gutter="16">
					<a-col :span="12">
						<a-space fill>
							<a-button type="primary" @click="openModal()" shape="round">
								<template #icon><icon-plus /></template>
								添加商家
							</a-button>
						</a-space>
					</a-col>
				</a-row>

				<a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
					@page-change="onPageChange" :scroll="{ x: 2140 }" @page-size-change="onPageSizeChange">
					<template #columns>
						<a-table-column title="ID" data-index="id" :width="80" />
						<a-table-column title="图片" data-index="image" :width="80">
							<template #cell="{ record }">
								<a-image :src="record.avatar" width="50" />
							</template>
						</a-table-column>
						<a-table-column title="名称" data-index="name" :width="350">
							<template #cell="{ record }">
								<div>{{ record.name }} <span v-if="record.multi_biz_id > 0">[多]</span></div>
								<div>
									<a-typography-text type="warning">
										<a-rate :default-value="record.star" readonly />
									</a-typography-text>
								</div>
							</template>
						</a-table-column>
						<a-table-column title="统一信用代码号" data-index="uscc" :width="200">
							<template #cell="{ record }">
								<a-space fill direction="vertical">
									<a-typography-text type="primary" v-if="record.uscc" underline>
										{{ record.uscc }}
									</a-typography-text>
									<a-typography-text type="secondary" v-if="record.shop_address" color="gray">
										{{ record.shop_address }}
									</a-typography-text>
								</a-space>
							</template>
						</a-table-column>

						<a-table-column title="评论总数" data-index="comment_total" :width="100" />
						<a-table-column title="店铺电话" data-index="biz_phone" :width="150" />
						<a-table-column title="店主信息" data-index="master_name" :width="150" >
							<template #cell="{ record }">
								<div>{{record.master_name}}</div>
								<div>
									<a-typography-text type="secondary" v-if="record.master_phone" color="gray">
										{{ record.master_phone }}
									</a-typography-text>
								</div>
							</template>
						</a-table-column>
						<a-table-column title="营业时间" data-index="business_hours" :width="120" />

						<a-table-column title="普通会员折扣" data-index="normal_discount" :width="120" />
						<a-table-column title="套餐结算折扣" data-index="goods_price_discount" :width="120" />
						<a-table-column title="VIP会员折扣" data-index="vip_discount" :width="120" />
						<a-table-column title="状态" data-index="status" :width="120">
							<template #cell="{ record }">
								<a-tag :color="record.status === 1 ? 'green' : 'red'">{{ record.status === 1 ? '正常' :
									'禁用' }}</a-tag>
							</template>
						</a-table-column>
						<a-table-column title="创建时间" data-index="created_at" :width="180" />
						<a-table-column title="排序" data-index="sort_by" :width="100" />
						<a-table-column title="操作" align="center" :width="180" fixed="right">
							<template #cell="{ record }">
								<a-space size="mini">

									<a-link @click="openAdminsModal(record)">
										管理员
									</a-link>
									
									<a-popconfirm position="left" content="确定要删除这个业务吗？" @ok="handleDelete(record.id)">
										<a-link status="danger">
											删除
										</a-link>
									</a-popconfirm>
									<a-link @click="openBizMenuModal(record)">
										更多
									</a-link>
								</a-space>
							</template>
						</a-table-column>
					</template>
				</a-table>
			</a-space>
		</a-card>

		<a-modal v-model:visible="modalVisible" width="850px" :draggable="true" :title="formData.id ? '编辑商家' : '添加商家'"
			@before-ok="handleSubmit" @cancel="closeModal">
			<a-form :model="formData" ref="formRef" layout="vertical">
				<a-row :gutter="16">
					<a-col :span="12">
						<a-form-item field="name" label="名称" :rules="[{ required: true }]">
							<a-input v-model="formData.name" placeholder="请输入名称" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="uscc" label="统一信用代码号" :rules="[{ required: true }]">
							<a-input v-model="formData.uscc" placeholder="请输入统一信用代码号" />
						</a-form-item>
					</a-col>
				</a-row>

				<a-row :gutter="16">
					<a-col :span="12">
						<a-form-item label="背景图">
							<a-upload list-type="picture" v-model="formData.image" :custom-request="handleUpload"
								:limit="1" :file-list="fileList" image-preview @before-remove="beforeRemove" />
							<template #extra>
								<div>请保持图片比例为3:2，格式为pg/png</div>
							</template>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="头像">
							<a-upload list-type="picture" v-model="formData.avatar" :custom-request="handleAvatarUpload"
								:limit="1" :file-list="avatarFileList" image-preview
								@before-remove="beforeAvatarRemove" />
							<template #extra>
								<div>请保持图片比例为1:1，格式为pg/png</div>
							</template>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="sort_by" label="排序">
							<a-input-number v-model="formData.sort_by" placeholder="请输入排序" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="biz_phone" label="店铺电话" :rules="[{ required: true }]">
							<a-input v-model="formData.biz_phone" placeholder="请输入店铺电话" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="shop_address" label="店铺地址" :rules="[{ required: true }]">
							<a-input v-model="formData.shop_address" placeholder="请输入店铺地址" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="pos" label="位置">
							<a-input v-model="formData.pos" placeholder="请输入位置" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="normal_discount" label="普通会员折扣">
							<a-input-number v-model="formData.normal_discount" placeholder="请输入普通会员折扣" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="goods_price_discount" label="套餐结算折扣">
							<a-input-number v-model="formData.goods_price_discount" placeholder="请输入套餐结算折扣" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="vip_discount" label="VIP会员折扣">
							<a-input-number v-model="formData.vip_discount" placeholder="请输入VIP会员折扣" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="opentime" label="开门时间">
							<a-input-number v-model="formData.opentime" placeholder="请输入开门时间(0-24)" :min="0" :max="24" />
							<template #extra>
								<div>请输入0-24之间的数字，如8表示8:00</div>
							</template>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="close_time" label="关门时间">
							<a-input-number v-model="formData.close_time" placeholder="请输入关门时间(0-24)" :min="0" :max="24" />
							<template #extra>
								<div>请输入0-24之间的数字，如16表示16:00</div>
							</template>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="multi_id" label="总店">
							<a-select v-model="formData.multi_biz_id" placeholder="请选择总店">
								<a-option v-for="multi in multiList" :key="multi.id" :value="multi.id" :label="multi.name">
									{{ multi.name }}
								</a-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="master_name" label="店主姓名">
							<a-input v-model="formData.master_name" placeholder="请输入店主姓名" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="master_phone" label="店主电话">
							<a-input v-model="formData.master_phone" placeholder="请输入店主电话" />
						</a-form-item>
					</a-col>
				</a-row>

				<a-row :gutter="16">
					<a-col :span="24">
						<a-form-item field="service" label="服务项">
							<a-input-tag v-model="formData.service" placeholder="请输入服务项，按回车键添加" :max-tag-count="10"
								allow-clear />
						</a-form-item>
					</a-col>
				</a-row>

				<a-row :gutter="16">
					<a-col :span="24">
						<a-form-item field="desc" label="商家描述">
							<div class="markdown-editor-container">
								<v-md-editor v-model="formData.desc" @upload-image="handleUploadImage" :disabled-menus="[]" height="300px" style="width: 100%;" />
							</div>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>

		<!-- 特别说明模态框 -->
		<a-modal v-model:visible="specialNoteModalVisible" width="600px" :draggable="true" title="编辑特别说明"
			@before-ok="handleSpecialNoteSubmit" @cancel="closeSpecialNoteModal">
			<a-form :model="specialNoteForm" ref="specialNoteFormRef" layout="vertical">
				<a-form-item field="special_note" label="特别说明">
					<a-textarea v-model="specialNoteForm.special_note" placeholder="请输入特别说明信息" :rows="6" />
				</a-form-item>
			</a-form>
		</a-modal>

		<!-- 标签管理模态框 -->
		<a-modal v-model:visible="tagModalVisible" width="800px" :draggable="true" title="管理商家标签"
			@cancel="closeTagModal">
			<div class="tag-management">
				<a-row :gutter="16">
					<a-col :span="12">
						<div class="tag-section">
							<h4>已关联标签</h4>
							<div class="tag-list">
								<a-tag v-for="tag in bizTags" :key="tag.id" color="blue" closable
									@close="removeTag(tag.id)">
									{{ tag.name }}
								</a-tag>
								<div v-if="bizTags.length === 0" class="empty-tags">
									暂无关联标签
								</div>
							</div>
						</div>
					</a-col>
					<a-col :span="12">
						<div class="tag-section">
							<h4>添加标签</h4>
							<a-select v-model="selectedTagId" placeholder="请选择要添加的标签" style="width: 100%" allow-clear>
								<a-option v-for="tag in availableTags" :key="tag.id" :value="tag.id" :label="tag.name">
									{{ tag.name }}
								</a-option>
							</a-select>
							<a-button type="primary" @click="addTag" style="margin-top: 10px;"
								:disabled="!selectedTagId">
								添加标签
							</a-button>
						</div>
					</a-col>
				</a-row>
			</div>
		</a-modal>

		<a-modal v-model:visible="bizMenuModalVisible" width="500px" :footer="false" :draggable="true" title="业务菜单"
			@cancel="closeBizMenuModal">
			<a-space fill size="large">
				<a-button @click="openModal(currentBiz)">
						编辑
				</a-button>
				<a-button @click="openSpecialNoteModal(currentBiz)">
					提示
				</a-button>
				<a-button @click="openTagModal(currentBiz)">
					标签
				</a-button>
			</a-space>
		</a-modal>

		<!-- 管理员管理抽屉 -->
		<a-drawer v-model:visible="adminsDrawerVisible" width="900px" title="商家管理员管理"
			@cancel="closeAdminsDrawer">
			<div class="admins-management">
				<a-space fill direction="vertical" size="large">
					<!-- 管理员列表 -->
					<a-table :data="adminList" :loading="adminLoading" :bordered="{ cell: true }" :scroll="{ x: 600 }">
						<template #columns>
							<a-table-column title="ID" data-index="id" :width="80" />
							<a-table-column title="手机号" data-index="phone" :width="120" />
							<a-table-column title="角色" data-index="role" :width="100">
								<template #cell="{ record }">
									<a-tag :color="record.role === 'super' ? 'red' : 'blue'">
										{{ record.role === 'super' ? '超级管理员' : '普通管理员' }}
									</a-tag>
								</template>
							</a-table-column>
							<a-table-column title="状态" data-index="status" :width="100">
								<template #cell="{ record }">
									<a-tag :color="record.status === 1 ? 'green' : 'red'">
										{{ record.status === 1 ? '正常' : '禁用' }}
									</a-tag>
								</template>
							</a-table-column>
							<a-table-column title="创建时间" data-index="created_at" :width="180" />
							<a-table-column title="操作" align="center" :width="120" fixed="right">
								<template #cell="{ record }">
									<a-space size="mini">
										<a-link @click="openAdminModal(record)">
											编辑
										</a-link>
										<a-link v-if="record.role !== 'super'" @click="toggleAdminStatus(record)">
											{{ record.status === 1 ? '禁用' : '启用' }}
										</a-link>
										<a-popconfirm v-if="record.role !== 'super'" position="left" content="确定要删除这个管理员吗？" @ok="handleDeleteAdmin(record.id)">
											<a-link status="danger">
												删除
											</a-link>
										</a-popconfirm>
									</a-space>
								</template>
							</a-table-column>
						</template>
					</a-table>
				</a-space>
			</div>

			<template #footer>
				<a-button type="primary" @click="openAdminModal()" shape="round">
					<template #icon><icon-plus /></template>
					添加管理员
				</a-button>
			</template>
		</a-drawer>

		<!-- 管理员编辑模态框 -->
		<a-modal v-model:visible="adminModalVisible" width="500px" :draggable="true" :title="adminForm.id ? '编辑管理员' : '添加管理员'"
			@before-ok="handleAdminSubmit" @cancel="closeAdminModal">
			<a-form :model="adminForm" ref="adminFormRef" layout="vertical">
				<a-form-item field="user_id" label="会员ID" :rules="[{ required: true }]">
					<a-input v-model="adminForm.user_id" placeholder="请输入会员ID" />
				</a-form-item>
				<a-form-item field="role" label="角色">
					<a-select v-model="adminForm.role" placeholder="请选择角色">
						<a-option value="normal">普通管理员</a-option>
						<a-option value="super">超级管理员</a-option>
					</a-select>
					<template #extra>
						第一个管理员，无论任何角色，都为超级管理员
					</template>
				</a-form-item>
				<a-form-item field="status" label="状态">
					<a-select v-model="adminForm.status" placeholder="请选择状态">
						<a-option :value="1">正常</a-option>
						<a-option :value="0">禁用</a-option>
					</a-select>
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>

<style scoped>
.markdown-editor-container {
	border: 1px solid #d9d9d9;
	border-radius: 6px;
	overflow: hidden;
	width: 100%;
}

.markdown-editor-container :deep(.v-md-editor) {
	border: none;
	width: 100%;
}

.markdown-editor-container :deep(.v-md-editor__toolbar) {
	border-bottom: 1px solid #f0f0f0;
}

.markdown-editor-container :deep(.v-md-editor__editor-wrapper) {
	border: none;
	width: 100%;
}
</style>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { UploadRequest, RequestOption, FileItem } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryBizList, submitBizForm, delBiz, BizRecord, updateSpecialNote, getBizTags, addBizTag, removeBizTag } from '@/api/biz';
import { queryAllBizTag, BizTagRecord } from '@/api/bizTag';
import { uploadFile } from '@/api/upload';
import { queryBizAdminList, submitBizAdminForm, delBizAdmin, updateBizAdminStatus, queryAllAdmins, BizAdminRecord, AdminRecord } from '@/api/bizAdmin';
import VMdEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import githubTheme from '@kangc/v-md-editor/lib/theme/github';
import '@kangc/v-md-editor/lib/theme/style/github.css';
import createEmojiPlugin from '@kangc/v-md-editor/lib/plugins/emoji/index';
import '@kangc/v-md-editor/lib/plugins/emoji/emoji.css';
import createTodoListPlugin from '@kangc/v-md-editor/lib/plugins/todo-list/index';
import '@kangc/v-md-editor/lib/plugins/todo-list/todo-list.css';
import createAlignPlugin from '@kangc/v-md-editor/lib/plugins/align/index';
import createLineNumbertPlugin from '@kangc/v-md-editor/lib/plugins/line-number/index';
import createCopyCodePlugin from '@kangc/v-md-editor/lib/plugins/copy-code/index';
import '@kangc/v-md-editor/lib/plugins/copy-code/copy-code.css';
import createHighlightLinesPlugin from '@kangc/v-md-editor/lib/plugins/highlight-lines/index';
import '@kangc/v-md-editor/lib/plugins/highlight-lines/highlight-lines.css';
import { getAllMulti,MultiRecord } from '@/api/multi';

// 配置v-md-editor
VMdEditor.use(githubTheme);
VMdEditor.use(createEmojiPlugin());
VMdEditor.use(createTodoListPlugin());
VMdEditor.use(createAlignPlugin());
VMdEditor.use(createLineNumbertPlugin());
VMdEditor.use(createCopyCodePlugin());
VMdEditor.use(createHighlightLinesPlugin());

const { loading, setLoading } = useLoading(true);
const modalVisible = ref(false);
const specialNoteModalVisible = ref(false);
const tagModalVisible = ref(false);
const formRef = ref();
const specialNoteFormRef = ref();
const fileList = ref<FileItem[]>([]);

// 搜索表单数据
const searchForm = reactive({
	search: '',
	tag_ids: [] as number[],
	multi_biz_id:'',
});

// 所有标签数据
const allTags = ref<BizTagRecord[]>([]);

// 标签管理相关变量
const bizTags = ref<BizTagRecord[]>([]);
const availableTags = ref<BizTagRecord[]>([]);
const selectedTagId = ref<number | null>(null);
const currentBizId = ref<number>(0);
const currentBiz = ref<BizRecord>();

// 格式化service字段的辅助函数
const formatServiceField = (service: string | string[] | undefined): string[] => {
	if (Array.isArray(service)) {
		return service;
	}
	if (typeof service === 'string' && service) {
		return service.split('@');
	}
	return [];
};

const basePagination = {
	current: 1,
	pageSize: 10,
	total: 0,
};

const pagination = reactive({
	...basePagination,
});

const generateFormData = () => {
	return {
		id: 0,
		name: '',
		image: '',
		avatar: '',
		sort_by: 0,
		biz_phone: '',
		shop_address: '',
		uscc: '',
		service: [] as string[],
		pos: '',
		normal_discount: 0,
		goods_price_discount: 0,
		vip_discount: 0,
		opentime: 0,
		close_time: 0,
		desc: '',
		multi_biz_id: '',
		master_name: '',
		master_phone: '',
	};
};

const specialNoteForm = ref({
	id: 0,
	special_note: '',
});

const formData = ref(generateFormData());

const renderData = ref<BizRecord[]>([]);

const fetchData = async () => {
	setLoading(true);
	try {
		const { data } = await queryBizList({
			current: pagination.current,
			pageSize: pagination.pageSize,
			search: searchForm.search || undefined,
			tag_ids: searchForm.tag_ids.length > 0 ? searchForm.tag_ids.join(',') : undefined,
			multi_biz_id: searchForm.multi_biz_id,
		});
		renderData.value = data.list;
		pagination.total = data.total;
	} catch (err) {
		Message.error('获取业务列表失败');
	} finally {
		setLoading(false);
	}
};

const onPageChange = (current: number) => {
	pagination.current = current;
	fetchData();
};

const onPageSizeChange = (pageSize: number) => {
	pagination.pageSize = pageSize;
	pagination.current = 1;
	fetchData();
};

const multiList = ref<MultiRecord[]>([]);
const fetchMulti = async () => {
	const { data } = await getAllMulti();
	multiList.value = data;
};

const openModal = (record?: BizRecord) => {
	
	if (record) {
		formData.value = {
			id: record.id,
			name: record.name,
			image: record.image,
			avatar: record.avatar || '',
			sort_by: record.sort_by,
			biz_phone: record.biz_phone || '',
			shop_address: record.shop_address || '',
			uscc: record.uscc || '',
			service: formatServiceField(record.service),
			pos: record.pos || '',
			normal_discount: record.normal_discount || 0,
			goods_price_discount: record.goods_price_discount || 0,
			vip_discount: record.vip_discount || 0,
			opentime: record.opentime || 0,
			close_time: record.close_time || 0,
			desc: record.desc || '',
			multi_biz_id: record.multi_biz_id || '',
			master_name: record.master_name || '',
			master_phone: record.master_phone || '',
		};
		fileList.value = [{ uid: '1', url: record.image } as FileItem];
	} else {
		formData.value = generateFormData();
		fileList.value = [];
	}
	modalVisible.value = true;
};

const closeModal = () => {
	modalVisible.value = false;
	formData.value = generateFormData();
};

const handleUpload = async (option: any): Promise<UploadRequest> => {
	try {
		const { onProgress, onError, onSuccess, fileItem } = option;

		const uploadFormData = new FormData();
		uploadFormData.append('file', fileItem.file);
		const { data } = await uploadFile(uploadFormData);
		formData.value.image = data.url;

		fileList.value = [{ url: data.url } as FileItem];
		Message.success('上传成功');
		return {
			abort: () => { },
		};
	} catch (err) {
		Message.error('上传失败');
		return {
			abort: () => { },
		};
	}
};

const beforeRemove = async (fileItem: FileItem): Promise<boolean> => {
	formData.value.image = '';
	fileList.value = [];
	return true;
};

const avatarFileList = ref<FileItem[]>([]);

const handleAvatarUpload = async (option: any): Promise<UploadRequest> => {
	try {
		const { onProgress, onError, onSuccess, fileItem } = option;
		const uploadFormData = new FormData();
		uploadFormData.append('file', fileItem.file);
		const { data } = await uploadFile(uploadFormData);
		formData.value.avatar = data.path;
		avatarFileList.value = [{ url: data.url } as FileItem];
		Message.success('上传成功');
		return {
			abort: () => { },
		};
	} catch (err) {
		Message.error('上传失败');
		return {
			abort: () => { },
		};
	}
};

const beforeAvatarRemove = async (fileItem: FileItem): Promise<boolean> => {
	formData.value.avatar = '';
	avatarFileList.value = [];
	return true;
};

// 富媒体编辑框图片上传方法
const handleUploadImage = async (event: any, insertImage: any) => {
	try {
		// 创建文件输入元素
		const input = document.createElement('input');
		input.type = 'file';
		input.accept = 'image/*';
		
		input.onchange = async (e: any) => {
			const file = e.target.files[0];
			if (!file) {
				Message.warning('请选择要上传的图片');
				return;
			}

			// 检查文件类型
			if (!file.type.startsWith('image/')) {
				Message.error('只能上传图片文件');
				return;
			}

			// 检查文件大小（限制为5MB）
			const maxSize = 5 * 1024 * 1024; // 5MB
			if (file.size > maxSize) {
				Message.error('图片大小不能超过5MB');
				return;
			}

			try {
				const uploadFormData = new FormData();
				uploadFormData.append('file', file);
				
				const { data } = await uploadFile(uploadFormData);
				
				// 插入图片到编辑器
				insertImage({
					url: data.url,
					alt: file.name,
					title: file.name
				});
				
				Message.success('图片上传成功');
			} catch (err) {
				console.error('图片上传失败:', err);
				Message.error('图片上传失败，请重试');
			}
		};
		
		// 触发文件选择
		input.click();
	} catch (err) {
		console.error('图片上传失败:', err);
		Message.error('图片上传失败，请重试');
	}
};

const handleSubmit = async (done: (closed: boolean) => void) => {
	setLoading(true);
	try {
		// 处理service字段，将数组转换为@分隔的字符串
		const submitData = {
			...formData.value,
			service: Array.isArray(formData.value.service) ? formData.value.service.join('@') : formData.value.service
		};

		const res = await submitBizForm(submitData);
		Message.success('操作成功');
		closeModal();
		fetchData();
		done(true);
	} catch (err) {
		done(false);
	} finally {
		setLoading(false);
	}
};

const handleDelete = async (id: number) => {
	try {
		await delBiz(id);
		Message.success('删除成功');
		fetchData();
	} catch (err) {
		Message.error('删除失败');
	}
};

const resetSearch = () => {
	searchForm.search = '';
	searchForm.tag_ids = [];
	searchForm.multi_biz_id = '';
	pagination.current = 1;
	fetchData();
};

const openSpecialNoteModal = (record: BizRecord) => {
	specialNoteForm.value.id = record.id;
	specialNoteForm.value.special_note = record.special_note || '';
	specialNoteModalVisible.value = true;
};

const handleSpecialNoteSubmit = async (done: (closed: boolean) => void) => {
	setLoading(true);
	try {
		const res = await updateSpecialNote(specialNoteForm.value);
		Message.success('特别说明更新成功');
		closeSpecialNoteModal();
		fetchData();
		done(true);
	} catch (err) {
		done(false);
	} finally {
		setLoading(false);
	}
};

const closeSpecialNoteModal = () => {
	specialNoteModalVisible.value = false;
	specialNoteForm.value = {
		id: 0,
		special_note: '',
	};
};

const handleSearch = () => {
	pagination.current = 1;
	fetchData();
};

// 获取所有标签
const fetchAllTags = async () => {
	try {
		const response = await queryAllBizTag();
		allTags.value = response.data;
	} catch (err) {
		Message.error('获取标签列表失败');
	}
};

// 标签管理相关方法
const openTagModal = async (record: BizRecord) => {
	currentBizId.value = record.id;
	tagModalVisible.value = true;
	selectedTagId.value = null;

	// 获取商家已关联的标签
	await fetchBizTags(record.id);

	// 获取所有可用标签
	await fetchAvailableTags();
};

const closeTagModal = () => {
	tagModalVisible.value = false;
	bizTags.value = [];
	availableTags.value = [];
	selectedTagId.value = null;
	currentBizId.value = 0;
};

const fetchBizTags = async (bizId: number) => {
	try {
		const response = await getBizTags(bizId);
		bizTags.value = response.data;
	} catch (err) {
		Message.error('获取商家标签失败');
	}
};

const fetchAvailableTags = async () => {
	try {
		const response = await queryAllBizTag();
		// 过滤掉已关联的标签
		const bizTagIds = bizTags.value.map((tag: BizTagRecord) => tag.id);
		availableTags.value = (response.data as BizTagRecord[]).filter((tag: BizTagRecord) => !bizTagIds.includes(tag.id));
	} catch (err) {
		Message.error('获取可用标签失败');
	}
};

const addTag = async () => {
	if (!selectedTagId.value) {
		Message.warning('请选择要添加的标签');
		return;
	}

	try {
		await addBizTag({
			biz_id: currentBizId.value,
			tag_id: selectedTagId.value
		});
		Message.success('添加标签成功');

		// 重新获取数据
		await fetchBizTags(currentBizId.value);
		await fetchAvailableTags();

		selectedTagId.value = null;
	} catch (err) {
		Message.error('添加标签失败');
	}
};

const removeTag = async (tagId: number) => {
	try {
		await removeBizTag({
			biz_id: currentBizId.value,
			tag_id: tagId
		});
		Message.success('删除标签成功');

		// 重新获取数据
		await fetchBizTags(currentBizId.value);
		await fetchAvailableTags();
	} catch (err) {
		Message.error('删除标签失败');
	}
};

const bizMenuModalVisible = ref(false);
const openBizMenuModal = (record: BizRecord) => {
	currentBiz.value = record;
	bizMenuModalVisible.value = true;
};

const closeBizMenuModal = () => {
	bizMenuModalVisible.value = false;
	currentBiz.value = undefined;
};

// 管理员管理相关变量
const adminsDrawerVisible = ref(false);
const adminModalVisible = ref(false);
const adminLoading = ref(false);
const adminFormRef = ref();
const adminList = ref<BizAdminRecord[]>([]);
const availableAdmins = ref<AdminRecord[]>([]);

const adminForm = ref({
	id: 0,
	biz_id: 0,
	user_id: 0,
	role: 'normal' as 'super' | 'normal',
	status: 1,
});

// 管理员管理相关方法
const openAdminsModal = async (record: BizRecord) => {
	currentBizId.value = record.id;
	adminsDrawerVisible.value = true;
	await fetchAdminList(record.id);
	await fetchAvailableAdmins(record.id);
};

const closeAdminsDrawer = () => {
	adminsDrawerVisible.value = false;
	adminList.value = [];
	availableAdmins.value = [];
	currentBizId.value = 0;
};

const fetchAdminList = async (bizId: number) => {
	adminLoading.value = true;
	try {
		const response = await queryBizAdminList({ biz_id: bizId });
		adminList.value = response.data;
	} catch (err) {
		Message.error('获取管理员列表失败');
	} finally {
		adminLoading.value = false;
	}
};

const fetchAvailableAdmins = async (bizId: number) => {
	try {
		const response = await queryAllAdmins({ biz_id: bizId });
		availableAdmins.value = response.data;
	} catch (err) {
		Message.error('获取可用管理员列表失败');
	}
};

const openAdminModal = (record?: BizAdminRecord) => {
	if (record) {
		adminForm.value = {
			id: record.id,
			biz_id: record.biz_id,
			user_id: record.user_id,
			role: record.role,
			status: record.status,
		};
	} else {
		adminForm.value = {
			id: 0,
			biz_id: currentBizId.value,
			user_id: 0,
			role: 'normal',
			status: 1,
		};
	}
	adminModalVisible.value = true;
};

const closeAdminModal = () => {
	adminModalVisible.value = false;
	adminForm.value = {
		id: 0,
		biz_id: 0,
		user_id: 0,
		role: 'normal',
		status: 1,
	};
};

const handleAdminSubmit = async (done: (closed: boolean) => void) => {
	try {
		await submitBizAdminForm(adminForm.value);
		Message.success('操作成功');
		closeAdminModal();
		await fetchAdminList(currentBizId.value);
		await fetchAvailableAdmins(currentBizId.value);
		done(true);
	} catch (err) {
		done(false);
	}
};

const handleDeleteAdmin = async (id: number) => {
	try {
		await delBizAdmin(id);
		Message.success('删除成功');
		await fetchAdminList(currentBizId.value);
		await fetchAvailableAdmins(currentBizId.value);
	} catch (err) {
		Message.error('删除失败');
	}
};

const toggleAdminStatus = async (record: BizAdminRecord) => {
	try {
		const newStatus = record.status === 1 ? 0 : 1;
		await updateBizAdminStatus({ id: record.id, status: newStatus });
		Message.success('状态更新成功');
		await fetchAdminList(currentBizId.value);
	} catch (err) {
		Message.error('状态更新失败');
	}
};

onMounted(() => {
	fetchData();
	fetchAllTags();
	fetchMulti();
});
</script>

<style scoped lang="less">
.container {
	padding: 0 20px 20px 20px;
}

.tag-management {
	.tag-section {
		h4 {
			margin-bottom: 16px;
			color: #1d2129;
			font-weight: 500;
		}

		.tag-list {
			min-height: 120px;
			padding: 12px;
			border: 1px solid #e5e6eb;
			border-radius: 6px;
			background-color: #f7f8fa;

			.empty-tags {
				color: #86909c;
				text-align: center;
				padding: 20px 0;
			}
		}
	}
}

.admins-management {
	padding: 0;
}
</style>

<script lang="ts">
export default {
	name: 'BizList',
};
</script>